package com.gt.gt_securitytest.controller;


import com.gt.gt_securitytest.entity.MyUserDetails;
import com.gt.gt_securitytest.entity.Users;
import com.gt.gt_securitytest.utils.JwtUtil;
import jakarta.annotation.Resource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/security")
public class LoginController {
    @Resource
    AuthenticationManager authenticationManager;

    @PostMapping("/login")
    public String login(@RequestBody Users users){
        //提供参数
        Authentication authentication = new UsernamePasswordAuthenticationToken(users.getUsername(),users.getPassword());
        //主动调用认证
        Authentication authenticate = authenticationManager.authenticate(authentication);

        if (!authenticate.isAuthenticated())
            return "认证失败";

        /*
        * 验证成功后就能获得MyUserDetails
        * */
        MyUserDetails principal = (MyUserDetails) authenticate.getPrincipal();
        //生成jwt
        Map<String, Object> map = new HashMap<>();
        map.put("user",principal);
        String token = JwtUtil.createJWT("gtboy",36000000,map);
        return token;
    }

}
